package com.lanswon.icc.auth.config;

import com.lanswon.icc.auth.mobile.SmsCodeAuthenticationFilter;
import com.lanswon.icc.auth.mobile.SmsCodeAuthenticationProvider;
import com.lanswon.icc.auth.service.MyUserDetailService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * SecurityConfig 用于保护oauth要开放的资源，同时主要作用于client端以及token的认证(Bearer auth)
 * SecurityConfig优先于ResourceServerConfig，且在SecurityConfig 不拦截oauth要开放的资源，在ResourceServerConfig
 * 中配置需要token验证的资源，也就是我们对外提供的接口。
 *
 * 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源
 *
 * 是默认情况下spring security的http配置
 */
@Component
@AllArgsConstructor
public class SmsSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final MyUserDetailService myUserDetailsService;


    private final AuthenticationSuccessHandler myAuthenticationSuccessHandler;


//



    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();

        //设置AuthenticationManager
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //设置成功失败处理器
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
//        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationSuccessHandler);

        //设置provider
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService);

        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }



    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        String encode = bCryptPasswordEncoder.encode("123456");

        System.out.println(encode);

        String random = RandomStringUtils.randomNumeric(6);
        System.out.println(random);
    }

}
